import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:agora_rtc_engine/rtc_local_view.dart' as RtcLocalView;
import 'package:agora_rtc_engine/rtc_remote_view.dart' as RtcRemoteView;
import 'package:agora_rtc_engine/src/impl/media_recorder_impl.dart';
import 'package:star_author/controller/app_package_info_getx_controller.dart';
import 'package:star_author/env/env_config.dart';
import 'package:star_author/event_bus/open_live_good_event.dart';
import 'package:star_author/model/channel.dart';
import 'package:star_author/provider/index.dart';
import 'package:star_author/utils/http/api_manager.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/rong_im/rong_im.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/toast_util.dart';
import 'package:star_author/utils/websocket_manage/websocket_handler.dart';
import 'package:star_author/views/stream/dialog/anchor_info.dart';
import 'package:star_author/views/stream/dialog/connect_microphone_management.dart';
import 'package:star_author/views/stream/dialog/on_line_user_dialog.dart';
import 'package:star_author/views/stream/dialog/scan_result_dialog.dart';
import 'package:star_author/views/stream/dialog/select_evaluate_dialog.dart';
import 'package:star_author/views/stream/widget/live_announcement.dart';
import 'package:star_author/widgets/button_widget.dart';
import 'package:star_author/widgets/cover_widget.dart';
import 'package:star_author/widgets/dialog/bottom_sheet.dart';
import 'package:star_author/widgets/dialog/get_dialog.dart';
import 'package:star_author/widgets/qr_code_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:provider/provider.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:wakelock/wakelock.dart';

import '../../config/api.dart';
import '../../config/base_configuration.dart';
import '../../event_bus/global_event_bus.dart';
import '../../event_bus/rong_im_message_event.dart';
import '../../utils/common_util/log_util.dart';
import '../../utils/common_util/shared_preferences/sp_util.dart';
import '../../utils/common_util/toast/custom_toast.dart';
import '../../utils/event.dart';
import '../../utils/media_recorder_util.dart';
import '../../utils/utils.dart';
import '../../widgets/dialog/dialog_type.dart';
import '../../widgets/dialog/sure_dialog.dart';
import 'BarrageWidget.dart';
import 'dialog/anchor_select_list_bottom_sheet.dart';
import 'dialog/beauty_dialog.dart';
import 'dialog/good_list.dart';
import 'dialog/live_detection_info.dart';
import 'dialog/live_management.dart';
import 'model/live_good_list_entity.dart';
import 'mute_widget.dart';
import 'open_live_current_good.dart';
import 'stream_rtc_top.dart';

//TODO:主播端
class OpenLive extends StatefulWidget {
  const OpenLive({Key? key}) : super(key: key);

  @override
  _OpenLiveState createState() => _OpenLiveState();
}

class _OpenLiveState extends State<OpenLive> {
  late StreamSubscription<OpenLiveGoodEvent> _streamSubscriptionstream2;

  int _id = 0;

  late final RtcEngine _engine;

  ScrollController sController = ScrollController();

  Map studioDetail = {};

  String anchorImage = "";
  int anchorId = 0;
  String anchorName = "";

  late Timer check_user_timer;

  //轮训检测是否有连接融云成功
  initRongTimer() async {
    int status = await RongIMClient.getConnectionStatus() ?? 0;
    ChatRoomInfo? chatRoomInfo;
    await RongIMClient.getChatRoomInfo(
            StreamConf.channelKey, 20, RCChatRoomMemberOrder.Asc)
        .then((value) {
      if (value != null) {
        chatRoomInfo = value;
      } else {
        RongUtil.joinChatRoom();
      }
    });
    if (chatRoomInfo == null) return;
    int index_where = chatRoomInfo?.memberInfoList?.indexWhere(
            (element) => element.userId.toString() == _id.toString()) ??
        -1;
    if (status == RCConnectionStatus.Connected) {
      LogUtil.v("当前已经连接");
      if (index_where == -1) {
        LogUtil.v("当前用户不在直播间，加入直播间");
        Sentry.captureMessage("当前用户不在直播间，加入直播间---Connected,直播间Id:$_id");
        RongUtil.joinChatRoom();
      } else {
        LogUtil.v("当前用户在直播间，不需要直播间");
      }
    } else {
      RongUtil.connect(
        () async {
          //判断当前用户是否在直播间
          if (index_where == -1) {
            LogUtil.v("当前用户不在直播间，加入直播间");
            Sentry.captureMessage("当前用户不在直播间，加入直播间---DisConnected,直播间Id:$_id");
            RongUtil.joinChatRoom();
          }
        },
        "anchor",
      );
    }
  }

  @override
  void initState() {
    super.initState();
    PackageInfo? packageInfo =
        Get.find<AppPackageInfoGetXController>().packageInfo;
    String localVersion = packageInfo?.version ?? "";
    HttpUtil.commonRequest(
      Get.context!,
      ApiManager.settings,
      queryParameters: {
        "app_version": localVersion,
      },
      isLoading: false,
      isErrorToast: false,
    ).then((value) {
      Provider.of<ConfigProvider>(Get.context!, listen: false)
          .set(key: "settings", value: value.data);
    });
    check_user_timer = Timer.periodic(Duration(seconds: 30), (timer) {
      initRongTimer();
    });
    _initEngine();
  }

  @override
  void dispose() {
    super.dispose();
    Wakelock.disable();
    _local_videos_timer.cancel();
    check_user_timer.cancel();
    Event.off("price_range_changed");
    valueNotifier.removeListener(update);
    _streamSubscriptionstream?.cancel();
    _streamSubscriptionstream2.cancel();
    RongUtil.disconnect();
    StreamConf.barrages = [];
    StreamConf.token = "";
    _engine.destroy();
    _timer?.cancel();
    timer?.cancel();
    onlineTimer?.cancel();
    count_timer?.cancel();
  }

  late ChannelModel channelModel;

  void update() {
    ///刷新重建界面
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      updateState(() {});
    });
  }

  updateState(VoidCallback fn) {
    if (mounted) {
      setState(fn);
    }
  }

  bool canFocus = false;

  Timer? timer;

  List userConnectList = [];

  initConnectCount() async {
    await HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/studios/${StreamConf.liveId}/user_studios',
      isLoading: false,
      isErrorToast: false,
    ).then((value) {
      updateState(() {
        userConnectList = value.data['data'] ?? [];
        ConnectCount = value.data['meta']['total_count'] ?? 0;
      });
    });
  }

  int ConnectCount = 0;
  StreamSubscription<RongIMMessageEvent>? _streamSubscriptionstream;

  List<LiveGoodListData> dataList = [];

  late Timer _local_videos_timer;

  //检测本地视频是否超过10个，如果超过10个就提示上传数据
  initTimer() {
    _local_videos_timer = Timer.periodic(
      Duration(minutes: EnvConfig.isProd() ? 10 : 1),
      (timer) {
        init();
      },
    );
  }

  init() async {
    List<FileSystemEntity> fileList = await MediaRecorderUtil.getFileList();
    //没有到10个就不提示上传
    if (fileList.length < (EnvConfig.isProd() ? 10 : 2)) {
      return;
    } else {
      List<Map> localVideoList =
          SpUtil.getObjectList(MediaRecorderUtil.localKey) ?? [];
      int count = localVideoList.length;
      if (dataList.length > 0) {
        count -= 1;
      }
      DialogUtil.showMyDialog(
        dialogType: DialogType.detection_local_video,
        param: {
          'count': count,
        },
        rightButtonOnTap: () {
          CustomToast.show('开始上传');
          if (dataList.length > 0) {
            localVideoList.removeWhere((element) =>
                element['id'].toString() == dataList[0].id.toString());
          }
          for (int i = 0; i < fileList.length; i++) {
            String str = fileList[i].path;
            int first = str.lastIndexOf('/');
            int last = str.lastIndexOf('.');
            String id = str.substring(first + 1, last);
            Future.delayed(Duration(milliseconds: 1000 * i), () {
              MediaRecorderUtil.upload(
                id,
                path: fileList[i].path,
              );
            });
          }
        },
      );
    }
  }

  initStream() {
    initTimer();
    _streamSubscriptionstream =
        GlobalEventBus().bus.on<RongIMMessageEvent>().listen((event) async {
      if (event.message.content != null) {
        TextMessage msg = event.message.content as TextMessage;
        Map map = json.decode(msg.extra!);
        if (map['operation'] == OperationKey.user_to_connect) {
          initConnectCount();
          Event.emit("GetInitConnectCountInDialog");
        }
      }
    });
    _streamSubscriptionstream2 =
        GlobalEventBus().bus.on<OpenLiveGoodEvent>().listen((event) async {
      dataList = event.liveGoodListData;
      isDown = false;
      updateState(() {});
    });
  }

  _initEngine() async {
    RongIMClient.onConnectionStatusChange = (int? connectionStatus) {
      if (connectionStatus == RCConnectionStatus.DisConnected) {
        Sentry.captureMessage("用户主动断开,直播间Id:${_id}");
        initRongTimer();
      } else if (connectionStatus == RCConnectionStatus.TokenIncorrect) {
        Sentry.captureMessage("token 非法，此时无法连接 im，需重新获取 token,直播间Id:${_id}");
        initRongTimer();
      } else if (connectionStatus == RCConnectionStatus.Timeout) {
        Sentry.captureMessage(
            "自动连接超时，SDK 将不会继续连接，用户需要做超时处理，再自行调用 connectWithToken 接口进行连接,直播间Id:${_id}");
        initRongTimer();
      } else if (connectionStatus == RCConnectionStatus.Suspend) {
        Sentry.captureMessage(
            '连接暂时挂起（多是由于网络问题导致），SDK 会在合适时机进行自动重连,直播间Id:${_id}');
        initRongTimer();
      } else if (connectionStatus == RCConnectionStatus.Connected) {
        Sentry.captureMessage('连接成功,直播间Id:${_id}');
        setState(() {
          is_show_barrage = true;
        });
      } else if (connectionStatus == RCConnectionStatus.Connecting) {
        Sentry.captureMessage('连接中');
      } else if (connectionStatus == RCConnectionStatus.NetworkUnavailable) {
        Sentry.captureMessage('网络不可用,直播间Id:${_id}');
      } else if (connectionStatus == RCConnectionStatus.KickedByOtherClient) {
        initRongTimer();
        Sentry.captureMessage('该账号在其他设备登录，导致当前设备掉线,直播间Id:${_id}');
      }
    };
    RongIMClient.onJoinChatRoom = (String? targetId, int? status) {
      if (status == RCOperationStatus.Success) {
        setState(() {
          is_show_barrage = true;
        });
      } else if (status == RCOperationStatus.Failed) {
        Sentry.captureMessage('加入直播间失败');
        //当前页面才需要
        RongUtil.joinChatRoom();
      }
    };
    UserProvider userProvider =
        Provider.of<UserProvider>(context, listen: false);
    _id = userProvider.user?['id'] ?? 0;
    StreamConf.liveId = userProvider.user?['maintain_studios'][0]['id'] ?? 0;
    WebSocketHandle.subscribeLiveChannel();
    StreamConf.channelKey =
        userProvider.user?['maintain_studios'][0]['key'] ?? "";
    isConnect =
        userProvider.user?['maintain_studios'][0]['interaction'] ?? false;
    Wakelock.enable();
    RongUtil.connect(() async {}, "anchor");
    // 设置用户ID
    Sentry.configureScope((scope) {
      scope.user = SentryUser(id: _id.toString());
    });
    initStream();
    valueNotifier.addListener(update);
    _engine =
        await RtcEngine.createWithContext(RtcEngineContext(StreamConf.appid));
    StreamConf.barrages = [];
    _addListeners();
    var result = await API.getLiveInfo(StreamConf.liveId);
    initConnectCount();
    channelModel = ChannelModel.fromJson(result.data);
    StreamConf.channelModel = channelModel;

    studioDetail = result.data;
    anchorImage = studioDetail['avatar'] ?? '';
    anchorName = studioDetail['name'] ?? '';
    if (studioDetail['living_anchor'] != null) {
      anchorImage = studioDetail['living_anchor']['avatar'] ?? '';
      anchorName = studioDetail['living_anchor']['nickname'] ?? '';
      anchorId = studioDetail['living_anchor']['id'] ?? 0;
      MediaRecorderUtil.anchorId = anchorId;
    }

    StreamConf.token = await _getToken(StreamConf.channelKey);
    MediaRecorderUtil.mediaRecorderImpl = MediaRecorderImpl.getMediaRecorder(
      _engine,
      callback: MediaRecorderUtil.getCallBack(),
    );
    _engine.setCameraCapturerConfiguration(CameraCapturerConfiguration(
      preference: CameraCaptureOutputPreference.Manual,
      captureWidth: MyVideoDimensions.width,
      captureHeight: MyVideoDimensions.height,
      cameraDirection: CameraDirection.Rear, //后置摄像头
    ));
    await _engine.setVideoEncoderConfiguration(
      VideoEncoderConfiguration(
        //视频编码的帧率(fps)，默认值为 15
        frameRate: VideoFrameRate.Fps30,
        //视频编码的最小帧率(fps)，默认值为 -1
        minFrameRate: VideoFrameRate.Fps15,
        //1280*720
        bitrate: Bitrate.b_1280_x_720_30,
        minBitrate: Bitrate.b_1280_x_720_30,
        //视频尺寸
        dimensions: VideoDimensions(
          width: MyVideoDimensions.width,
          height: MyVideoDimensions.height,
        ),
        orientationMode: VideoOutputOrientationMode.FixedPortrait,
      ),
    );
    await _engine.enableVideo();
    //开启wifi加速
    _engine.enableWirelessAccelerate(true);
    await _engine.startPreview();
    await _engine.setChannelProfile(ChannelProfile.LiveBroadcasting);
    await _engine.setClientRole(ClientRole.Broadcaster);
    Future.delayed(Duration(seconds: 3), () async {
      //获取摄像头支持的最大放大范围
      _engine.getCameraMaxZoomFactor().then((value) {
        cameraMaxZoom = value ?? 10.0;
      }).catchError((e) {});
    });
    _engine.enableLastmileTest(); //网络测试
  }

  //摄像头支持的最大放大范围 ----tips iOS默认10倍
  double cameraMaxZoom = 10;

  bool? isCameraExposurePosition = false;
  bool? isCameraAutoFocus = false;
  bool? isCameraFocus = false;

  Future<String> _getToken(String channelKey) async {
    dynamic res = await API.getRTCToken({
      'role': 'host',
      'uid': this._id,
      'channel_name': channelKey,
    });
    dynamic token = res.data['token'];
    return token;
  }

  void getStudioDetail() async {
    var result = await API.getLiveInfo(StreamConf.liveId);
    channelModel = ChannelModel.fromJson(result.data);
    studioDetail = result.data;
    anchorImage = studioDetail['avatar'] ?? '';
    anchorName = studioDetail['name'] ?? '';
    if (studioDetail['living_anchor'] != null) {
      anchorImage = studioDetail['living_anchor']['avatar'] ?? '';
      anchorId = studioDetail['living_anchor']['id'] ?? 0;
      MediaRecorderUtil.anchorId = anchorId;
      anchorName = studioDetail['living_anchor']['nickname'] ?? '';
    }
    Get.bottomSheet(
      AnchorSelectListBottomSheet(
        studioDetail,
        (val) {
          onChangeAnchor(val);
        },
      ),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(16.w),
        ),
      ),
      barrierColor: Colors.transparent,
      isScrollControlled: true,
    );
    updateState(() {});
  }

  //重置美颜参数
  reset() {
    beauty.forEach((element) {
      if (element['type'] == "slider") {
        element['value'] = 0.0;
      } else if (element['suffix'] == darkLightLevel) {
        element['value'] = 1;
      } else if (element['suffix'] == contrast) {
        element['value'] = 1;
      } else if (element['suffix'] == ColorEnhancement) {
        element['button_value'] = 1;
        element['strength_value'] = 50.0;
        element['skin_protect_value'] = 100.0;
      }
    });
  }

  leave() async {
    dataList = [];
    if (dataList.length > 0) {
      if (!(dataList[0].show_price_options ?? false)) {
        CustomToast.show("当前还有货品在讲解，请结束讲解后下播");
        return;
      }
    }
    showGetDialog(
      AnchorOffline(
        sure: () async {
          try {
            EasyLoading.show(status: "请稍等...");
            MediaRecorderUtil.stopRecording();
            _engine.stopPreview();
            MediaRecorderUtil.releaseRecorder();
            _engine.stopRtmpStream(StreamConf.rtmpPushUrl);
            _engine.destroy();
            if (channelModel.isAnchor && isOpenLive) {
              //是否主播 并且开播的才需要调用接口
              await API.close(StreamConf.liveId);
            }
            WebSocketHandle.unSubscribeLiveChannel(); //取消订阅
            RongIMClient.forceRemoveChatRoomEntry(StreamConf.channelKey,
                StreamConf.chatRoomEntry, false, "", (code) {});
            reset();
            await RongUtil.quitChatRoom();
            await API.checkIfExists(StreamConf.liveId).then((value) {
              if (value.data['in_studio']) {
                //{in_studio: false}
                API.leave(StreamConf.liveId);
              }
            });
            Get.back();
          } catch (e) {
          } finally {
            EasyLoading.dismiss();
          }
        },
      ),
    );
  }

  _addListeners() {
    _engine.setEventHandler(RtcEngineEventHandler(
      warning: (warningCode) {},
      error: (errorCode) {},
      joinChannelSuccess: (channel, uid, elapsed) async {},
      cameraFocusAreaChanged: (Rect rect) {
        updateState(() {
          x = rect.x - 25;
          y = rect.y - 25;
        });
      },
      cameraExposureAreaChanged: (Rect rect) {},
      userJoined: (uid, elapsed) {},
      transcodingUpdated: () {},
      rtmpStreamingStateChanged: (String url, RtmpStreamingState state,
          RtmpStreamingErrorCode errCode) {
        //推流出错
        if (state == RtmpStreamingState.Failure) {
          //推流失败原因
          if (errCode != RtmpStreamingErrorCode.OK) {
            //监听到推流异常 上传到sentry 可帮助查看修复问题
            Sentry.captureMessage('推流地址:$url , 状态:$state, 错误码:$errCode');
            //主播网络出错
            DialogUtil.showMyDialog(
              dialogType: DialogType.rtmp_error_net_down_tips,
            );
          }
        }
      },
      rtmpStreamingEvent: (String url, RtmpStreamingEvent eventCode) {},
      userOffline: (uid, reason) {
        if (uid == remoteUserId &&
            [UserOfflineReason.Dropped, UserOfflineReason.Quit]
                .contains(reason)) {
          updateState(() {
            remoteUserId = 0;
            user_in_live = false;
            Event.emit("changed_user_in_live", user_in_live);
            HttpUtil.commonRequest(
              Get.context!,
              '/api/v1/studios/${StreamConf.liveId}/user_studios',
            ).then((value) {
              updateState(() {
                List data = value.data['data'] ?? [];
                int index = data.indexWhere((element) => element['id'] == uid);
                if (index != -1) {
                  DialogUtil.showMyDialog(
                      dialogType: DialogType.UserBreakConnectMicrophone,
                      buttonOnTap: () async {
                        userCloseConnect(uid);
                      });
                }
              });
            });
          });
        }
      },
      leaveChannel: (stats) {},
      localVideoStats: (LocalVideoStats stats) {
        LiveDetectionInfo.stats = stats;
      },
      userMuteVideo: (int userId, bool value) {
        if (userId == remoteUserId) {
          if (value) {
            updateState(() {
              user_in_live = false;
              remoteUserId = 0;
              isConnecting = false;
              Event.emit("changed_user_in_live", user_in_live);
              DialogUtil.showMyDialog(
                  dialogType: DialogType.UserBreakConnectMicrophone,
                  buttonOnTap: () async {
                    userCloseConnect(userId);
                  });
            });
          } else {
            updateState(() {
              user_in_live = true;
              Event.emit("changed_user_in_live", user_in_live);
            });
          }
        }
      },
      requestToken: () async {
        //更新token Token 已过期回调。
        String token2 = await _getToken(StreamConf.channelKey);
        StreamConf.token = token2;
        await _engine.joinChannel(
          token2,
          StreamConf.channelKey,
          null,
          _id,
          ChannelMediaOptions(),
        );
      },
      lastmileQuality: (NetworkQuality quality) {
        List<NetworkQuality> goodNetWork = [
          NetworkQuality.Good,
          NetworkQuality.Excellent,
          NetworkQuality.Poor,
          NetworkQuality.Unknown,
        ];
        if (goodNetWork.contains(quality)) {
          netWorkStatus = true;
        } else {
          netWorkStatus = false;
        }
        updateState(() {});
        _engine.disableLastmileTest();
      },
      remoteVideoStateChanged: (
        int uid,
        VideoRemoteState state,
        VideoRemoteStateReason reason,
        int elapsed,
      ) {
        if (uid != _id) {
          //远端用户关闭连麦
          updateState(() {
            if (state == VideoRemoteState.Stopped) {
              remoteUserId = 0;
              user_in_live = false;
            } else {
              user_in_live = true;
              remoteUserId = uid;
            }
            Event.emit("changed_user_in_live", user_in_live);
          });
        }
      },
    ));
  }

  userCloseConnect(int userId) async {
    int index =
        userConnectList.indexWhere((element) => element['id'] == userId);
    await RongUtil.operation(OperationKey.close_connecting_mic, {
      "user_id": userId,
      "connect_type": "disconnect",
      "nickname": userConnectList[index]['nickname'] ?? "",
    });
    //用户断开 不需要取反了 监听里面已经变成false 了
    await HttpUtil.commonRequest(
        Get.context!, '/api/v1/studios/${StreamConf.liveId}/touch_user_studio',
        method: HttpUtil.MethodPut,
        data: {
          "user_id": userId,
          "event": 'disconnect',
          "is_expired": user_in_live,
        }).then((value) async {
      await initConnectCount();
    });
  }

  //用户是否在直播间
  //false 创建连接成功之后再调用断连
  //true 没有创建连接成功
  bool user_in_live = false;

  buildLeftWidget() {
    if (isOpenLive) {
      return GestureDetector(
        child: Container(
          decoration: BoxDecoration(
            color: Color(0x4D000000),
            borderRadius: BorderRadius.circular(19.w),
          ),
          padding: EdgeInsets.only(
            left: 5.0.w,
            right: 15.0.w,
          ),
          height: 38.0.w,
          child: Row(
            children: [
              buildCircleCover(
                size: 30.w,
                cover: anchorImage,
              ),
              Container(
                margin: EdgeInsets.only(
                  left: 4.0.w,
                ),
                height: 38.0.w,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "主播 ${anchorName.length >= 10 ? anchorName.substring(0, 9) + "..." : anchorName}",
                      style: TextStyle(
                          fontSize: 12.0.sp,
                          color: Colors.white,
                          fontWeight: FontWeight.w500),
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        RoucesUtil.getAssetsIcon('ic_live_fire_lt', 12),
                        SizedBox(
                          width: 4.w,
                        ),
                        Text(
                          "${getLiveHeat(valueNotifier.value.view_count)} ｜  ${online_count} 在看",
                          style:
                              TextStyle(fontSize: 8.0.sp, color: Colors.white),
                        ),
                      ],
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
        onTap: () {
          Get.bottomSheet(OnLineUserDialog(),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.vertical(
                  top: Radius.circular(16.w),
                ),
              ),
              isScrollControlled: true);
        },
      );
    } else {
      return GestureDetector(
        child: Image.asset(
          'images/lt_common/close_icon.png',
          width: 24.w,
          height: 24.w,
        ),
        onTap: () {
          Get.back();
        },
      );
    }
  }

  buildMute(top) {
    return Positioned(
      child: Offstage(
        child: Container(
          child: MuteWidget(),
        ),
        offstage: !isOpenLive,
      ),
      top: top + 55.w,
    );
  }

  bool isMute = false; //是否静音 默认没有

  bool isConnect = false; //是否开启连麦

  bool isConnecting = false; //是否跟用户连麦中

  buildOpenLiveBottom() {
    if (isOpenLive) {
      return Positioned(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Offstage(
              child: Container(
                child: barrageList(
                  liveFrom: LiveFrom.Anchor,
                ),
                constraints: BoxConstraints(
                    minHeight: StreamConf.barrageMinHeight,
                    maxHeight: StreamConf.barrageMaxHeight),
                margin: EdgeInsets.only(
                  bottom: 10.w,
                ),
              ),
              offstage: !is_show_barrage,
            ),
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  if (dataList.length > 0)
                    Expanded(
                      child: Builder(
                        builder: (context) {
                          //显示选择
                          bool is_select =
                              (dataList[0].anchorEvaluationPriceRange ?? [])
                                      .length >
                                  0;
                          if (is_select) {
                            return Container(
                              height: 40.w,
                              margin: EdgeInsets.only(
                                right: 12.w,
                                left: 12.w,
                              ),
                              child: Text(
                                "已选估价\n${getPriceWithList(dataList[0].anchorEvaluationPriceRange ?? [], intl: true)}",
                                style: TextStyle(
                                  fontSize: 12.sp,
                                  color: rgba(51, 51, 51, 1),
                                ),
                                textAlign: TextAlign.center,
                              ),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(25),
                                color: rgba(255, 255, 255, 1),
                              ),
                            );
                          }
                          return GestureDetector(
                            child: Container(
                              height: 40.w,
                              margin: EdgeInsets.only(
                                right: 12.w,
                                left: 12.w,
                              ),
                              child: Text(
                                "选择估价",
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: Colors.white,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(25),
                                color: rgba(240, 69, 41, 1),
                              ),
                            ),
                            behavior: HitTestBehavior.opaque,
                            onTap: () {
                              //选择估价
                              Get.bottomSheet(
                                SelectEvaluateDialog(
                                  searchText: "",
                                  studioDetail: studioDetail,
                                  engine: _engine,
                                  data: dataList[0],
                                  muteCallBack: () {
                                    updateState(() {
                                      isMute = false;
                                    });
                                  },
                                  select_reference: {},
                                ),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.vertical(
                                    top: Radius.circular(16.w),
                                  ),
                                ),
                                barrierColor: Colors.transparent,
                                isScrollControlled: true,
                              );
                            },
                          );
                        },
                      ),
                    ),
                  GestureDetector(
                    child: Container(
                      //ic_live_connect_list ic_live_can_connect
                      child:
                          RoucesUtil.getAssetsIcon('ic_open_live_scan_lt', 40.w),
                      margin: EdgeInsets.only(
                        right: 12.w,
                      ),
                    ),
                    onTap: () {
                      if (studioDetail['select_anchors_list'] == null) {
                        CustomToast.show("该直播间未绑定讲解人列表");
                        Get.bottomSheet(
                          AnchorSelectListBottomSheet(
                            studioDetail,
                            (val) {
                              onChangeAnchor(val);
                            },
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.vertical(
                              top: Radius.circular(16.w),
                            ),
                          ),
                          barrierColor: Colors.transparent,
                          isScrollControlled: true,
                        );
                      } else {
                        QRCodeUtil.show(context, entrance: QRCodeDialog.stream,
                            callback: (val) {
                          if (val != null) {
                            //弹框
                            HttpUtil.commonRequest(
                              Get.context!,
                              "/api/v1/studios/${StreamConf.liveId}/backflows",
                              queryParameters: {
                                'q': val,
                              },
                              isLoading: true,
                              isErrorToast: false,
                            ).then((value) {
                              if ((value.data['data'] ?? []).length > 0) {
                                LiveGoodListData data =
                                    LiveGoodListData.fromJson(
                                        (value.data['data'] ?? [])[0]);
                                bool isStartExplain = false;
                                if (dataList.length > 0) {
                                  isStartExplain =
                                      (data.id == dataList[0].id) &&
                                          (data.anchorEvaluationPriceRange
                                                      ?.length ??
                                                  0) ==
                                              0;
                                }
                                //当前有录制的货品 并且扫码出来的货品没有录播 弹框
                                if (dataList.length > 0 &&
                                    (data.id != dataList[0].id) &&
                                    (data.recordingVideo?.isEmpty ?? false)) {
                                  CustomToast.show('当前有货品录制中');
                                  return;
                                }
                                Get.bottomSheet(
                                  ScanResultDialog(
                                    searchText: val,
                                    studioDetail: studioDetail,
                                    engine: _engine,
                                    isStartExplain: isStartExplain,
                                    data: data,
                                    muteCallBack: () {
                                      updateState(() {
                                        isMute = false;
                                      });
                                    },
                                  ),
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.vertical(
                                      top: Radius.circular(16.w),
                                    ),
                                  ),
                                  barrierColor: Colors.transparent,
                                  isScrollControlled: true,
                                );
                              } else {
                                CustomToast.show('找不到该编码的货品');
                              }
                            });
                          }
                        });
                      }
                    },
                  ),
                  Builder(builder: (context) {
                    if (isConnect) {
                      return GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                          width: 42.w,
                          height: 42.w,
                          decoration: BoxDecoration(
                            color: Color(0x4D000000),
                            borderRadius: BorderRadius.circular(50),
                          ),
                          child: Center(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Text(
                                  '$ConnectCount',
                                  style: TextStyle(
                                      fontSize: 16.sp,
                                      color: Color(0xFFFEBA07),
                                      fontWeight: FontWeight.w500),
                                ),
                                Image.asset(
                                  RoucesUtil.getAssets('ic_live_connect_list_lt'),
                                  width: 17.w,
                                  height: 10.w,
                                )
                              ],
                            ),
                          ),
                          margin: EdgeInsets.only(right: 12.w),
                        ),
                        onTap: () {
                          showDialog();
                        },
                      );
                    } else {
                      return GestureDetector(
                        child: Container(
                          //ic_live_connect_list ic_live_can_connect
                          child: RoucesUtil.getAssetsIcon(
                              'ic_live_can_connect_lt', 40.w),
                          margin: EdgeInsets.only(
                            right: 12.w,
                          ),
                        ),
                        onTap: () {
                          showDialog();
                        },
                      );
                    }
                  }),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                        width: 42.w,
                        height: 42.w,
                        decoration: BoxDecoration(
                          color: Color(0x4D000000),
                          borderRadius: BorderRadius.circular(50),
                        ),
                        child: Center(
                          child: Text(
                            '管理',
                            style: TextStyle(
                                fontSize: 14.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.w500),
                          ),
                        )),
                    onTap: () {
                      Get.bottomSheet(
                        LiveManagement(
                          leave: () {
                            Get.back();
                            if (remoteUserId != 0) {
                              DialogUtil.showMyDialog(
                                  dialogType:
                                      DialogType.AnchorOfflineWithUserConnect);
                            } else {
                              leave();
                            }
                          },
                          studioDetailMap: studioDetail,
                          engine: _engine,
                          isMute: isMute,
                          muteCallBack: (mute) {
                            updateState(() {
                              isMute = mute;
                            });
                          },
                          selectAnchorCallback: (result) async {
                            channelModel = ChannelModel.fromJson(result);

                            studioDetail = result;
                            if (studioDetail['living_anchor'] != null) {
                              anchorImage =
                                  studioDetail['living_anchor']['avatar'] ?? '';
                              anchorId =
                                  studioDetail['living_anchor']['id'] ?? 0;
                              MediaRecorderUtil.anchorId = anchorId;
                              anchorName = studioDetail['living_anchor']
                                      ['nickname'] ??
                                  '';
                            }
                            updateState(() {});
                          },
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.vertical(
                            top: Radius.circular(16.w),
                          ),
                        ),
                        barrierColor: Colors.transparent,
                        isScrollControlled: true,
                      );
                    },
                  ),
                  GestureDetector(
                    child: Container(
                      height: 40.w,
                      width: 40.w,
                      margin: EdgeInsets.only(left: 12.w),
                      alignment: Alignment.center,
                      child: Image.asset(
                        RoucesUtil.getAssets('bg_wait_bidder_list_lt'),
                        width: 40.w,
                        height: 40.w,
                        fit: BoxFit.cover,
                      ),
                    ),
                    onTap: () async {
                      if (anchorId == 0) {
                        CustomToast.show("请选择主播后进行货品处理");
                        return;
                      }
                      showModalBottomSheet(
                        builder: (BuildContext context) {
                          //构建弹框中的内容
                          return GoodList(
                            liveFrom: LiveFrom.Anchor,
                            totalCount: 0,
                            engine: _engine,
                            studioDetail: studioDetail,
                            id: _id,
                            muteCallBack: () {
                              updateState(() {
                                isMute = false;
                              });
                            },
                          );
                        },
                        backgroundColor: Colors.transparent, //重要
                        isScrollControlled: true,
                        context: context,
                      );
                    },
                  ),
                ],
              ),
              width: Get.width,
              margin: EdgeInsets.only(
                bottom: MediaQuery.of(context).padding.bottom + 18.0.w,
              ),
              padding: EdgeInsets.only(
                right: 12.w,
              ),
            ),
          ],
        ),
        bottom: 0,
      );
    } else {
      return Container(
        child: ButtonWidget(
          child: Container(
            child: Text(
              "开启直播间直播",
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w500,
                fontSize: 16.0.sp,
              ),
            ),
          ),
          type: ButtonType.bgGradientOrange2,
          height: 50.0,
          width: Get.width * 0.8,
          onPressed: () {
            countDown();
          },
        ),
        alignment: Alignment.bottomCenter,
        margin: EdgeInsets.only(bottom: 50.w),
      );
    }
  }

  bool netWorkStatus = true; //默认网络好

  //网络状态
  buildNetWorkStatus() {
    return Container(
      alignment: Alignment.center,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            'images/${netWorkStatus ? "network_success_lt" : "network_error_lt"}.png',
            width: 8.w,
            height: 8.w,
            fit: BoxFit.cover,
          ),
          SizedBox(
            width: 5.w,
          ),
          Text(
            "${netWorkStatus ? "网络良好" : "网络较差"}",
            style: TextStyle(fontSize: 12.sp, height: 1.5, color: Colors.white),
          ),
        ],
      ),
    );
  }

  bool isOnTap = false;

  buildCount() {
    if (isOpenLive) {
      return Container();
    } else {
      if (isOnTap) {
        return Center(
          child: Container(
            width: 100.w,
            height: 100.w,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(50.w),
              color: Color(0x4D000000),
            ),
            child: Center(
              child: Text(
                "$count",
                style: TextStyle(
                    fontSize: 68.sp,
                    color: Colors.white,
                    fontWeight: FontWeight.bold),
              ),
            ),
          ),
        );
      }
      return Container();
    }
  }

  bool isClear = false;

  double x = -50;
  double y = -50;

  buildConnectingWidget() {
    return Container(
      alignment: Alignment.center,
      width: 90.w,
      height: 130.w,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Image.asset(
            RoucesUtil.getAssets('ic_live_connecting_lt'),
            width: 90.w,
            height: 130.w,
          ),
          Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  '连接中..',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.white,
                  ),
                ),
                GestureDetector(
                  child: Container(
                    margin: EdgeInsets.only(
                      top: 9.w,
                    ),
                    alignment: Alignment.center,
                    child: Text(
                      '下一位',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.white,
                      ),
                    ),
                    width: 60.w,
                    height: 24.w,
                    decoration: BoxDecoration(
                      color: Colors.transparent,
                      border: Border.all(
                        color: Colors.white,
                      ),
                      borderRadius: BorderRadius.circular(
                        14.sp,
                      ),
                    ),
                  ),
                  onTap: () async {
                    int index = userConnectList
                        .indexWhere((element) => element['id'] == remoteUserId);
                    await RongUtil.operation(
                        OperationKey.close_connecting_mic, {
                      "user_id": remoteUserId,
                      "connect_type": "disconnect",
                      "nickname": userConnectList[index]['nickname'] ?? "",
                    });
                    await HttpUtil.commonRequest(Get.context!,
                        '/api/v1/studios/${StreamConf.liveId}/touch_user_studio',
                        method: HttpUtil.MethodPut,
                        data: {
                          "user_id": remoteUserId,
                          "event": 'disconnect',
                          "is_expired": !user_in_live,
                        }).then((value) async {
                      updateState(() {
                        remoteUserId = 0;
                      });
                      showDialog();
                    });
                  },
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  showDialog() {
    showMyBottomSheet(
      ConnectMicrophoneManagement(
        isConnect: isConnect,
        user_in_live: user_in_live,
        callBack: (val) {
          updateState(() {
            isConnect = val;
            if (!isConnect) {
              remoteUserId = 0;
              isConnecting = false;
            }
          });
        },
        userCallBack: (userId, String event) {
          initConnectCount();
          updateState(() {
            remoteUserId = userId;
            if (event == "connect") {
              isConnecting = true;
            } else {
              remoteUserId = 0;
              isConnecting = false;
            }
          });
        },
      ),
      callBack: (val) {
        initConnectCount();
      },
    );
  }

  int remoteUserId = 0;

  //本地画面
  buildView() {
    if (remoteUserId != 0) {
      if (user_in_live) {
        if (isBig) {
          return Container(
            width: ScreenUtil().screenWidth,
            height: ScreenUtil().screenHeight,
            child: RtcLocalView.SurfaceView(
              renderMode: VideoRenderMode.Hidden,
              mirrorMode: StreamConf.videoMirrorMode,
            ),
          );
        }
        return Container(
          width: ScreenUtil().screenWidth,
          height: ScreenUtil().screenHeight,
          child: RtcRemoteView.SurfaceView(
            channelId: StreamConf.channelKey,
            uid: remoteUserId,
            renderMode: StreamConf.renderMode,
          ),
        );
      } else {
        return Container(
          width: ScreenUtil().screenWidth,
          height: ScreenUtil().screenHeight,
          child: RtcLocalView.SurfaceView(
            renderMode: VideoRenderMode.Hidden,
            mirrorMode: StreamConf.videoMirrorMode,
          ),
        );
      }
    } else {
      return Container(
        width: ScreenUtil().screenWidth,
        height: ScreenUtil().screenHeight,
        child: RtcLocalView.SurfaceView(
          renderMode: VideoRenderMode.Hidden,
          mirrorMode: StreamConf.videoMirrorMode,
        ),
      );
    }
  }

  bool isBig = false; //本地是否切换为主播是大屏显示

  buildSmallView() {
    //ic_live_anchor_changed
    if (!user_in_live && remoteUserId != 0) {
      //用户没有在直播间
      return buildConnectingWidget();
    }
    if (remoteUserId == 0) {
      return Container();
    }
    if (isConnecting) {
      return Container(
        width: 90.w,
        height: 130.w,
        color: Colors.black,
        child: Stack(
          children: [
            Builder(builder: (context) {
              if (isBig) {
                return Container(
                  child: RtcRemoteView.SurfaceView(
                    channelId: StreamConf.channelKey,
                    uid: remoteUserId,
                    renderMode: StreamConf.renderMode,
                  ),
                );
              }
              return RtcLocalView.SurfaceView(
                renderMode: VideoRenderMode.Hidden,
                mirrorMode: StreamConf.videoMirrorMode,
              );
            }),
            Positioned(
              right: 0,
              top: 0,
              child: GestureDetector(
                child: RoucesUtil.getAssetsIcon('ic_live_anchor_changed_lt', 22.w),
                onTap: () {
                  setState(() {
                    isBig = !isBig;
                  });
                },
              ),
            )
          ],
        ),
      );
    } else {
      return Container();
    }
  }

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top + 20.0;
    return WillPopScope(
        child: GestureDetector(
          child: Stack(
            children: [
              buildView(),
              Positioned(
                child: Container(
                  width: Get.width - 12.w - 12.w,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      buildLeftWidget(),
                      Row(
                        children: [
                          if (isOpenLive) buildNetWorkStatus(),
                          InkWell(
                            child: Center(
                              child: Image.asset(
                                "images/lt_live/switch_camera.png",
                                width: 36.0.w,
                                height: 36.0.w,
                              ),
                            ),
                            onTap: () async {
                              await _engine.switchCamera();
                            },
                          )
                        ],
                      ),
                    ],
                  ),
                ),
                top: top,
                left: 12.0.w,
              ),
              buildMute(top),
              buildOpenLiveBottom(),
              buildCount(),
              if (isOpenLive)
                Positioned(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      buildTitle(),
                      LiveAnnouncement(),
                    ],
                  ),
                  top: top + 50.w,
                  left: 12.w,
                ),
              //连麦显示--
              Positioned(
                child: buildSmallView(),
                bottom: MediaQuery.of(context).padding.bottom +
                    7.w +
                    50.w +
                    12.w +
                    25.w,
                right: 8.w,
              ),
              if (isOpenLive)
                openLiveCurrentGood(
                  isOpenLive: isOpenLive,
                ),
            ],
          ),
          onTapUp: (TapUpDetails details) {
            try {
              _engine.setCameraFocusPositionInPreview(
                  details.localPosition.dx, details.localPosition.dy);
              _engine.setCameraExposurePosition(
                  details.localPosition.dx, details.localPosition.dy);
            } catch (e) {
              LogUtil.v(e);
            }
          },
          onDoubleTap: () {
            _previousScale = 1;
            _scale = 1;
            _engine.setCameraZoomFactor(1);
          },
          onScaleStart: _handleOnScaleStart,
          onScaleUpdate: (ScaleUpdateDetails details) {
            _handleOnScaleUpdate(details);
          },
        ),
        onWillPop: () {
          if (isOpenLive) {
            leave();
          } else {
            Get.back();
          }
          return Future.value(false);
        });
  }

  _handleOnScaleUpdate(ScaleUpdateDetails details) {
    setState(() {
      _scale = (_previousScale * details.scale).clamp(1.0, cameraMaxZoom);
      _engine.setCameraZoomFactor(_scale);
      // 更新当前位置
    });
  }

  _handleOnScaleStart(ScaleStartDetails details) {
    setState(() {
      _previousScale = _scale;
    });
  }

  double _scale = 1.0;

  double _previousScale = 0;

  late Timer? _timer = null;

  bool is_show_barrage = false; //是否加载弹幕

  int count = 3;

  openLive() async {
    //调用接口开播
    EasyLoading.show(status: "开播中...");
    timer = Timer.periodic(Duration(minutes: 1), (timer) {
      initConnectCount();
    });
    try {
      if (channelModel.isAnchor && !channelModel.isSwitch) {
        //是否主播 并且没有开播的才需要调用接口
        await API.open(StreamConf.liveId);
      }
      RongUtil.joinChatRoom();
      await HttpUtil.commonRequest(Get.context!,
              ApiManager.studios + "/${StreamConf.liveId}/check_if_exists")
          .then((value) async {
        if (!value.data['in_studio']) {
          //{in_studio: false}
          await API.join(StreamConf.liveId);
        } else {
          await API.leave(StreamConf.liveId);
          await API.join(StreamConf.liveId);
        }
      });
      valueNotifier.setCount(1);
      await _engine.joinChannel(
        StreamConf.token,
        StreamConf.channelKey,
        null,
        _id,
        ChannelMediaOptions(),
      );
      _engine.startRtmpStreamWithoutTranscoding(StreamConf.rtmpPushUrl);
      StreamConf.engine = _engine;
      await getCount();

      onlineTimer = Timer.periodic(Duration(seconds: 30), (timer) {
        getCount();
      });

      getStudioDetail();
    } catch (e) {
      isOpenLive = false;
      count = 3;
      updateState(() {});
      await RongUtil.quitChatRoom();
      await API.close(StreamConf.liveId);
      await _engine.leaveChannel();
      _engine.stopRtmpStream(StreamConf.rtmpPushUrl);
      await API.leave(StreamConf.liveId);
      ToastUtil.show("开播失败,请再次开播重试");
      WebSocketHandle.unSubscribeLiveChannel();
    } finally {
      EasyLoading.dismiss();
    }
  }

  ///直播间发送切换讲解人通知
  Future<Message?> sendChangeAnchorMessage() async {
    TextMessage txtMessage = new TextMessage();
    Map map = {'operation': OperationKey.change_anchor, 'data': {}};
    txtMessage.extra = json.encode(map);
    Message? msg = await RongIMClient.sendMessage(
        RCConversationType.ChatRoom, StreamConf.channelKey, txtMessage);

    return msg;
  }

  void onChangeAnchor(map) {
    HttpUtil.commonRequest(
      Get.context!,
      "/api/v1/studios/${studioDetail['id'] ?? ''}/change_anchor/${map['id'] ?? ''}",
      isLoading: true,
      method: HttpUtil.MethodPut,
    ).then((value) async {
      if (value.statusCode == 201) {
        CustomToast.show("切换讲解主播成功");
        sendChangeAnchorMessage();
        updateState(() {});
        HttpUtil.commonRequest(
                Get.context!, '/api/v1/studios/${StreamConf.liveId}')
            .then((value) {
          studioDetail = value.data;
          channelModel = ChannelModel.fromJson(value.data);
          if (studioDetail['living_anchor'] != null) {
            anchorImage = studioDetail['living_anchor']['avatar'] ?? '';
            anchorId = studioDetail['living_anchor']['id'] ?? 0;
            MediaRecorderUtil.anchorId = anchorId;
            anchorName = studioDetail['living_anchor']['nickname'] ?? '';
          }
          updateState(() {});
        });
      }
    });
  }

  getCount() async {
    if (Get.currentRoute == "/OpenLive") {
      int? count = await RongUtil.getChatRoomCount();
      updateState(() {
        online_count = count!;
      });
    }
  }

  Timer? count_timer;

  int online_count = 0;

  bool isOpenLive = false; //开启直播

  late Timer? onlineTimer = null;

  buildTitle() {
    if (dataList.length == 0) {
      return Container();
    }
    return GestureDetector(
      child: Container(
        width: Get.width - 24.w,
        margin: EdgeInsets.only(
          bottom: 10.w,
        ),
        padding: EdgeInsets.symmetric(
          horizontal: 12.w,
          vertical: 8.w,
        ),
        decoration: BoxDecoration(
          color: rgba(255, 255, 255, 0.90),
          borderRadius: BorderRadius.circular(4.w),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            if (!isDown)
              Text(
                dataList[0].goods?.title ?? "",
                style: TextStyle(
                  fontSize: 14.sp,
                  color: rgba(51, 51, 51, 1),
                ),
              ),
            Container(
              margin: EdgeInsets.only(
                top: isDown ? 0 : 4.w,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Text(
                        "最终估价 ",
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: rgba(51, 51, 51, 1),
                        ),
                      ),
                      Text(
                        "${(dataList[0].priceRange ?? []).length == 0 ? "暂无估价" : "${getPriceWithList(
                            dataList[0].priceRange ?? [],
                            intl: true,
                          )}"}",
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: rgba(224, 32, 32, 1),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Text(
                        !isDown ? "收起" : "展开",
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: rgba(153, 153, 153, 1),
                        ),
                      ),
                      SizedBox(
                        width: 3.w,
                      ),
                      RotatedBox(
                        quarterTurns: !isDown ? 2 : 4,
                        child: RoucesUtil.getAssetsIcon('ic_live_down_lt', 9),
                      )
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        setState(() {
          isDown = !isDown;
        });
      },
    );
  }

  bool isDown = false;

  countDown() {
    count = 4;
    isOnTap = true;
    updateState(() {
      count--;
    });
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      updateState(() {
        count--;
      });
      if (count == 0) {
        updateState(() {
          isOpenLive = true;
        });
        openLive();
        _timer!.cancel();
      }
    });
  }
}
